/**
 * 
 */
package com.newtribe.security.cert;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.X509Certificate;

import org.bouncycastle.asn1.x509.X509Name;
import org.bouncycastle.jce.PKCS10CertificationRequest;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.util.encoders.Base64;

/**
 * @author newtribe
 *
 */
public class Pkcs10Request {

	
	public String generateRequest(String keystorePath ,char[] passwd ,String certAlias ,String keyAlias,String signAlgo)throws Exception {
		
	    KeyStore keystore =KeyStore.getInstance("jks") ;
	    InputStream in =new FileInputStream (keystorePath) ;
	    keystore.load(in ,passwd);
	    in.close();
	    X509Certificate cert  =(X509Certificate)keystore.getCertificate(certAlias) ;
	    PrivateKey privateKey =(PrivateKey)keystore.getKey(keyAlias, passwd) ;
	    PublicKey pks=cert.getPublicKey();
		
		return generateRequest(cert,privateKey ,signAlgo) ;
		
		
	}

	
	public String generateRequest(X509Certificate cert ,PrivateKey privkey ,String signAlgo )throws Exception {

		   if (cert == null) {
		     throw new Exception( " has no public key (certificate)");
		   }
		   //this is impl by sun api .
//		   PKCS10 request = new PKCS10(cert.getPublicKey());
//		  
//		   // Construct an X500Signer object, so that we can sign the request    if (sigAlgName == null) {        // If no signature algorithm was specified at the command line,        // we choose one that is compatible with the selected private key        String keyAlgName = privKey.getAlgorithm();        if (keyAlgName.equalsIgnoreCase("DSA")           || keyAlgName.equalsIgnoreCase("DSS")) {        sigAlgName = "SHA1WithDSA";        } else if (keyAlgName.equalsIgnoreCase("RSA")) {        sigAlgName = "MD5WithRSA";        } else {        throw new Exception("Cannot derive signature algorithm");        }    }
//
//		   Signature signature = Signature.getInstance(signAlgo);
//		   signature.initSign(privkey);
//		   X500Name subject = new X500Name( cert.getSubjectDN().toString());
//		   X500Signer signer = new X500Signer(signature, subject);
//
//		   // Sign the request and base-64 encode it
//		   request.encodeAndSign(signer);
//		  // request.print(System.out);
		   
		   
//		   ASN1EncodableVector v = new ASN1EncodableVector();
//		   DERConstructedSet s1 = new DERConstructedSet(v);

		   X509Name subjectDn =new X509Name(cert.getSubjectDN().toString());
		   PKCS10CertificationRequest req = new PKCS10CertificationRequest(signAlgo,subjectDn, 
				   cert.getPublicKey(), null, privkey);

		   ByteArrayOutputStream buffer =new ByteArrayOutputStream();
		   PEMWriter pemWrt = new PEMWriter(new OutputStreamWriter(buffer));

		   pemWrt.writeObject(req);
		   pemWrt.close();

		   String recert =new String(buffer.toByteArray());
		   // String recert=new String(Base64.encode(req.getEncoded()));
		   return recert ;
	}
}
